import { gantt } from 'dhtmlx-gantt'
import { usePltI18nStore } from '@/stores/i18n-plt'
import { useUserStore } from '@/stores/user.js'

// 初始化国际化存储
const pltI18nStore = usePltI18nStore()
const { taskName, startTime, duration } = pltI18nStore.pltI18n.cisdi.gczx.frontEnd.gantt
const store = useUserStore()

/**
 * 任务状态颜色映射 - 仅用于计划进度条
 */
export const riskGanttColor = (status) => {
  switch (status) {
    case 'TODO':
      return '#ebebeb'
    case 'DOING':
      return '#eec871'
    case 'DONE':
      return '#8abb9bff'
    case 'OVER':
      return '#f1afafff'
    default:
      return '#ebebeb'
  }
}

/**
 * 任务状态深色映射 - 用于计划进度条的进度填充
 */
const riskGanttDarkColor = (status) => {
  switch (status) {
    case 'TODO':
      return '#606266'
    case 'DOING':
      return '#ff9500'
    case 'DONE':
      return '#4a9e65'
    case 'OVER':
      return '#ff4949'
    default:
      return '#606266'
  }
}

/**
 * 甘特图配置与渲染核心函数
 */
export const renderGantt = (ganttDom, tasks) => {
  console.log(tasks)
  // 重置甘特图配置
  gantt.clearAll()
  gantt.resetLightbox()
  
  // 1. 基础配置
  gantt.config.date_format = '%Y-%m-%d'
  gantt.config.readonly = true
  gantt.config.task_height = 100 // 行高容纳双进度条
  gantt.config.min_column_width = 120
  gantt.config.auto_types = false
  
  // 2. 表格列配置
  gantt.config.columns = [
    { name: 'text', tree: true, label: taskName, width: '*', min_width: 250, resize: true },
    { name: 'start_date', label: startTime, min_width: 100, align: 'center' },
    { name: 'duration', label: duration, width: 80, align: 'center' },
    { name: 'isCrux', label: '是否关键路径', min_width: 120, align: 'center',
      // template: function (obj) {
      //       let textHtml = ''
      //       if (obj.isCrux == true) {
      //           // 正常延期
      //           textHtml =
      //               "<img src='@/assets/isCrux.png' style='width:20px;height:20px;'>"
      //       }
      //   }
    }
  ]

  // 3. 任务条模板 - 核心实现
  gantt.templates.task_text = function(start, end, task) {
    const progressWidth = task.progress * 100 + '%'
    // 计划进度条颜色（根据状态动态获取）
    const planColor = riskGanttColor(task.status)
    const planDarkColor = riskGanttDarkColor(task.status)
    // 实际进度条颜色（固定为#299cb4）
    const actualColor = '#50799aff'
    const actualDarkColor = '#005AA6'

    return `
      <div class="gantt_task_double_container">
        <!-- 计划进度条（上）- 使用riskGanttColor着色 -->
        <div class="gantt_plan_task">
          <div class="gantt_task_line_inner" style="width:100%; height:100%; background-color: ${planColor}">
            <div class="gantt_task_progress_inner" style="width: ${progressWidth}; height:100%; background-color: ${planDarkColor}"></div>
            <div class="gantt_task_content">${task.text}</div>
          </div>
        </div>
        
        <!-- 间隔区（20px） -->
        <div class="gantt_task_gap"></div>
        
        <!-- 实际进度条（下）- 固定为#299cb4 -->
        ${task.sj_start_date && task.sj_end_date ? `
          <div class="gantt_actual_task">
            <div class="gantt_actual_task_line" style="width:100%; height:100%; background-color: ${actualColor}">
              <div class="gantt_actual_task_progress" style="width: ${progressWidth}; height:100%; background-color: ${actualDarkColor}"></div>
              <div class="gantt_actual_task_content">${task.text}</div>
            </div>
          </div>
        ` : `
          <div class="gantt_actual_task empty-actual">
            <div class="gantt_actual_task_content">暂无实际进度数据</div>
          </div>
        `}
      </div>
    `
  }

  // 4. 任务条样式类
  gantt.templates.task_class = function(start, end, task) {
    const classes = ['custom-task']
    if (task.status) classes.push(task.status)
    if (task.sj_start_date && task.start_date !== task.sj_start_date) {
      classes.push('has-difference')
    }
    return classes.join(' ')
  }

  // 5. 实际进度条位置计算
  gantt.templates.actual_task_pos = function(task) {
    if (!task.sj_start_date || !task.sj_end_date) return { left: 0, width: 0 }
    
    const planStart = gantt.date.parseDate(task.start_date)
    const planLeft = gantt.posFromDate(planStart)
    const actualStart = gantt.date.parseDate(task.sj_start_date)
    const actualLeft = gantt.posFromDate(actualStart)
    const actualEnd = gantt.date.parseDate(task.sj_end_date)
    const actualWidth = gantt.posFromDate(actualEnd) - actualLeft

    return { 
      left: actualLeft - planLeft,
      width: actualWidth 
    }
  }

  // 6. 提示框配置
  gantt.plugins({ tooltip: true })
  gantt.templates.tooltip_text = function (start, end, task) {
    return `
      <div class="gantt_tooltip">
        <p>任务名称: ${task.text}</p>
        <p>进度: ${(task.progress * 100).toFixed(0)}%</p>
        <p v-if="task.remark">逾期说明: ${task.remark}</p>
      </div>
    `
  }

  // 7. 缩放配置
  const zoomConfig = {
    minColumnWidth: 40,
    maxColumnWidth: 150,
    levels: [
      [
        { unit: 'year', format: '%Y %M', step: 1 },
        {
          unit: 'week',
          step: 1,
          format: (date) => {
            const dateToStr = gantt.date.date_to_str('%m%d')
            const endDate = gantt.date.add(date, 6, 'day')
            return `${dateToStr(date)} ~ ${dateToStr(endDate)}`
          }
        }
      ],
      [
        { unit: 'month', format: '%M %Y', step: 1 },
        { unit: 'day', format: '%d %M', step: 1 }
      ]
    ],
    startDate: new Date('2024-01-01'),
    endDate: new Date('2029-01-01'),
    useKey: 'ctrlKey',
    trigger: 'wheel'
  }
  gantt.ext.zoom.init(zoomConfig)

  // 8. 语言配置
  gantt.i18n.setLocale(store?.loginInfo?.currentLangId === 'ZH_CN' ? 'cn' : '')

  // 9. 初始化与渲染
  gantt.init(ganttDom)
  gantt.parse(tasks)
  
  // 强制刷新任务显示
  gantt.eachTask(task => gantt.updateTask(task.id))
  gantt.render()
}

// 样式定义
const style = document.createElement('style')
style.textContent = `
  .gantt_task.custom-task {
    height: 100% !important;
    overflow: visible !important;
    box-sizing: border-box !important;
    border: none !important;
    background: transparent !important; /* 去掉任务条底色，设为透明 */
  }
  
  .gantt_task_double_container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 5px 0;
    box-sizing: border-box;
  }
  
  .gantt_plan_task {
    width: 100%;
    height: 80px;
    position: relative;
  }
  
  .gantt_task_line_inner {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 2px;
  }
  
  .gantt_task_progress_inner {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    border-radius: 2px 0 0 2px;
  }
  
  /* 20px间隔 */
  .gantt_task_gap {
    height: 20px;
    width: 100%;
  }
  
  /* 实际进度条样式 */
  .gantt_actual_task {
    width: 100%;
    height: 80px;
    position: relative;
  }
  
  .gantt_actual_task_line {
    position: absolute !important;
    top: 0 !important;
    left: 0 !important;
    height: 100% !important;
    border-radius: 2px;
  }
  
  .gantt_actual_task_progress {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    border-radius: 2px 0 0 2px;
  }
  
  .gantt_task_content,
  .gantt_actual_task_content {
    position: absolute;
    top: 0;
    left: 8px;
    height: 100%;
    line-height: 30px;
    font-size: 12px;
    color: #333;
    z-index: 2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: calc(100% - 16px);
  }
  
  .empty-actual .gantt_actual_task_content {
    color: #999;
  }
  
  .has-difference .gantt_actual_task_line {
    border: 1px dashed #ff9500;
  }
  
  /* 隐藏默认进度条元素 */
  .gantt_task_progress {
    display: none !important;
  }
`
document.head.appendChild(style)